package com.example.student.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Value("${rtsp.hls.output.directory}")
    private String hlsOutputDirectory;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 获取HLS输出目录的绝对路径
        File hlsDir = new File(hlsOutputDirectory);
        String absolutePath = hlsDir.getAbsolutePath();

        // 配置HLS静态资源访问，确保路径以斜杠结尾
        if (!absolutePath.endsWith(File.separator)) {
            absolutePath += File.separator;
        }

        // 在日志中打印路径信息，便于调试
        System.out.println("HLS目录绝对路径: " + absolutePath);

        registry.addResourceHandler("/hls-streams/**")
                .addResourceLocations("file:" + absolutePath);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .maxAge(3600);
    }
} 